package com.jiang.jetpackdemo.activity

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.StrictMode
import android.view.MotionEvent
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.AndroidViewModel
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.NavigationUI
import com.jiang.jetpackdemo.R
import com.jiang.jetpackdemo.fragment.PicRecommendFragment
import com.jiang.jetpackdemo.utils.exposedFileUri
import kotlinx.android.synthetic.main.activity_main2.*

const val PERMISSION_REQUEST_CODE = 1001

class Main2Activity : AppCompatActivity() {
    private lateinit var navController: NavController
    private lateinit var appBarConfiguration: AppBarConfiguration
    private val permissions by lazy {
        arrayOf(
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        )
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        initNav()
        checkPermissionAndCommit()
        exposedFileUri()
    }

    private fun initNav() {
        navController = Navigation.findNavController(
            this,
            R.id.fragment
        )
        appBarConfiguration = AppBarConfiguration.Builder(bnv.menu).build()
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration)
        NavigationUI.setupWithNavController(bnv, navController)
    }

    private fun checkPermissionAndCommit() {
        if (!hasPermissions(permissions)!!) {
            ActivityCompat.requestPermissions(
                this,
                permissions,
                PERMISSION_REQUEST_CODE
            )
        }
    }

    private fun hasPermissions(permissions: Array<String>): Boolean? {
        for (per in permissions) {
            if (ContextCompat.checkSelfPermission(
                    application,
                    per
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                return false
            }
        }
        return true
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        if (requestCode == PERMISSION_REQUEST_CODE) {
            val s =
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) "权限被允许" else "权限被拒绝"
            Toast.makeText(this, s, Toast.LENGTH_SHORT).show()
        }
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        PicRecommendFragment.onT(event!!)
        return true
    }
}
